
import Cookies from 'js-cookie'
import qs from "querystring";
// import { baseUrl } from 'env';
const baseUrl = "http://haosen.shmatching.com/jshs.saler";
// console.log()
export const myFetch = (url = '', params = {}, type = 'GET') => {
    let header = new Headers();
    header.set('Content-Type', 'application/x-www-form-urlencoded');
    header.set('token', Cookies.get('token'));
    return new Promise(function (resolve, reject) {
        let data = {
            method: type,
            headers: header,
            credentials: 'include',
            //   mode: 'no-cors'
        };
        if (type === 'GET') {
            let st = qs.stringify(params)
            if (st) url += '?' + st
        }
        if (type === 'POST') {
            data.body = JSON.stringify(params);
            header.set('Content-Type', 'application/json');
        };
         
        //   fetch( url, data)
        fetch(baseUrl + url, data)
            .then(
                (response) => {
                    if (response.ok) {
                        return response.json()
                    } else {
                        reject({
                            code: response.status
                        });
                    }
                }
            )
            .then((responseData) => {
                resolve(responseData)
                if (responseData.errorCode === 300004) {
                    Cookies.remove('token');
                    Cookies.remove('role');
                    Cookies.remove('userId');
                    Cookies.remove('pwd');
                    window.location.reload();
                }
            })
            .catch((err) => {
                reject(err);
            });
    });
};
